<template>
	<view class="container">
		<!-- 表单区域 -->
		<view class="form-section">
			<!-- 设备信息 -->
			<view class="form-group">
				<view class="form-title">设备信息</view>
				<view class="form-item">
					<text class="label">设备名称</text>
					<text class="value">{{ sbInfo.sbmc }}</text>
				</view>
				<view class="form-item">
					<text class="label">设备编号</text>
					<text class="value">{{ sbInfo.sbbh }}</text>
				</view>
				<view class="form-item">
					<text class="label">所在位置</text>
					<text class="value">{{ sbInfo.azdd }}</text>
				</view>
				<view class="form-item">
					<text class="label">润滑日期</text>
					<text class="value">{{ "" }}</text>
				</view>
				<view class="form-item">
					<text class="label">是否合格</text>
					<view class="isQualified">
						<view class="value"> {{ isQualified ? '是' : '否' }}</view>
						<up-switch :disabled="isDisabled" :size="14" v-model="isQualified"
							@change="qualifiedChange"></up-switch>
					</view>
				</view>
			</view>

			<!-- 润滑项目列表 -->
			<view class="form-group">
				<view class="form-header">
					<view class="form-title">润滑项目</view>
					<view class="quick-action" v-if="!isDisabled" :class="{ 'is-marked': isAllMarked }"
						@tap="toggleMarkAll">
						<text class="action-text">{{ isAllMarked ? '一键取消' : '一键合格' }}</text>
					</view>
				</view>
				<view class="check-list">
					<scroll-view id="scrollView" :scroll-y="true" :scroll-into-view="navIndex">
						<view v-for="(value,key,index) in maintenanceLevelOneDetailTwoCycleList" :key="index">
							<view>
								<text class="form-title"> {{ key }}</text>
								<view class="check-item" v-for="(item) in value" :key="item.id" slot="body"
									:id="item.id">
									<view class="check-header">
										<text class="label">工序内容</text>
										<text class="check-name">{{ item.maintenancecontent }}
											<text>[{{ item.status === '1' ? '正常' : '异常' }}]</text>
										</text>
									</view>

									<view class="check-header">
										<text class="label">合格标准</text>
										<text class="check-name">{{ item.eligibility }}</text>
									</view>

									<view class="check-options">
										<view :class="'option ' + (item.status === '1' ? 'active' : '')" data-value="正常"
											@tap="onOptionSelect(key,item.id,'1')">正常
										</view>
										<view :class="'option ' + (item.status === '0' ? 'active' : '')" data-value="异常"
											@tap="onOptionSelect(key,item.id,'0')">异常
										</view>
									</view>

									<!-- 异常情况下显示描述输入框 -->
									<view class="abnormal-content">
										<textarea v-if="item.status === '0'" :disabled="isDisabled"
											class="abnormal-desc" placeholder="请描述遇到的问题或者润滑情况"
											v-model="item.existingproblem"></textarea>

										<!-- 添加照片上传区域 -->
										<view class="upload-images">
											<view class="image-list">
												<view class="image-item"
													v-for="(img, imgIndex) in (item.fileList || [])" :key="imgIndex">
													<image :src="showPic(img.filePath)" mode="aspectFill"
														@tap="previewImage(item.fileList, imgIndex)" />
													<view v-if="!isDisabled" class="delete-btn"
														@tap.stop="deleteImage(item.fileList, imgIndex)">×
													</view>
												</view>
												<view class="upload-btn" :disabled="isDisabled"
													@tap="chooseImage(key,item.id)"
													v-if="!isDisabled &&(item.fileList === undefined || item.fileList.length < 3)">
													<text class="upload-icon">+</text>
													<text class="upload-text">上传照片</text>
													<text
														class="upload-desc">{{ item.fileList ? (3 - item.fileList.length) : 3 }}张
													</text>
												</view>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>

			<!-- 图片上传区域 -->
			<view class="form-group">
				<view class="form-title">现场照片</view>
				<view class="upload-section">
					<view class="image-list">
						<view class="image-item" v-for="(item, index) in byjhFileList" :key="index">
							<image :src="showPic(item.filePath)" mode="aspectFill"
								@tap="previewImage(byjhFileList,index)" />
							<view v-if="!isDisabled" class="delete-btn" @tap.stop="deleteImage(byjhFileList,index)">×
							</view>
						</view>
						<view :disabled="isDisabled" class="upload-btn" @tap="chooseByImage()" v-if="!isDisabled">
							<text class="upload-icon">+</text>
							<text class="upload-text">上传照片</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 备注信息 -->
			<view class="form-group">
				<view class="form-title">备注信息</view>
				<textarea :disabled="isDisabled" class="remarks" placeholder="请输入备注信息（选填）"
					v-model="byjhInfo.remarks"></textarea>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="footer-submit">
			<button v-if="true" :disabled="isDoubleClickDisabled" @tap="submitBzzConfirm">润滑确认
			</button>
		</view>
	</view>
</template>

<script>
	import dayjs from "dayjs/esm";
	import {
		bzzPermission,
		sbyPermission,
		Role,
		roleExists
	} from "../../../common/permission";

	export default {
		onLoad: function(option) {
			this.equipmentId = option.equipmentId;
			this.planId = option.id;
			this.baseUrl = this.$commonUnits.baseUrl;
			this.userId = this.$commonUnits.getUserId();
			this.userPic = uni.getStorageSync('user_pic');
			//获取设备基本信息
			this.getEquipmentInfo();
			//获取设备润滑项目
			// this.getMaintenanceLevelOneDetail();
			//获取计划消息
			// this.getByjh();
			//获取上传图片
			// this.getByjhFileList();
		},
		data() {
			return {
				baseUrl: "",
				isDisabled: false, //全局只读控制
				isDoubleClickDisabled: false, //双击防抖
				equipmentId: '',
				planId: '',
				isQualified: true,
				sbInfo: {
					sbmc: "",
					sbbh: "",
					azdd: ""
				},
				maintenanceLevelOneDetailList: [],
				maintenanceLevelOneDetailTwoCycleList: [],
				userPic: "",
				userId: "",
				byjhInfo: {},
				byjhFileList: [],
				bzzConfirmButtonVisitable: false,
				bzzRevokeConfirmButtonVisitable: false,
				sbyConfirmButtonVisitable: false,
				sbyRevokeConfirmButtonVisitable: false,
				submitData: [],
				isAllMarked: false, // 添加 isAllMarked 字段
				currentStatusText: "", // 列表显示当前状态文字
				navIndex: ""
			};
		},
		watch: {},
		updated() {},
		methods: {
			// 获取设备基本信息
			getEquipmentInfo() {
				this.$commonUnits.postRequest('sbby.zcglsbtzbiz.getZcglSbtzById.mobile', {
					id: this.equipmentId
				}).then(item => {
					this.sbInfo = item.res[0];
				})
			},
			getMaintenanceLevelOneDetail() {
				this.$commonUnits.postRequest('sbby.maintenancemobilebiz.getMaintenanceLevelOneDetail.mobile', {
					sbid: this.equipmentId,
				}).then(item => {
					this.maintenanceLevelOneDetailList = item.res.list;

					//处理润滑项目list数据 提取润滑部位 作为分组key，形成双层结构
					this.maintenanceLevelOneDetailTwoCycleList =
						this.$commonUnits.groupBy(this.maintenanceLevelOneDetailList, 'program');
				})
			},
			getByjh() {
				this.$commonUnits.postRequest('sbby.maintenancemobilebiz.getByjhById.mobile', {
					id: this.planId
				}).then(item => {
					this.byjhInfo = item.res;
					this.isQualified = this.byjhInfo.qualified === '1';
				})
			},
			getByjhFileList() {
				this.$commonUnits.postRequest('sbby.maintenancemobilebiz.getFilesById.mobile', {
					id: this.planId
				}).then(item => {
					this.byjhFileList = item.res;
				})
			},
			qualifiedChange(item) {
				if (item) {
					this.byjhInfo.qualified = '1';
					this.isQualified = true;
				} else {
					this.byjhInfo.qualified = '0';
					this.isQualified = false;
				}
			},

			//显示检验标准
			showEligibility(item) {
				uni.showModal({
					title: '合格标准',
					content: item,
					showCancel: false,
					success: (res) => {}
				});
			},
			// 选择检查结果
			onOptionSelect(key, id, status) {
				//只读状态
				if (this.isDisabled) {
					return 0;
				}
				//找到操作字段并赋值
				const index = this.maintenanceLevelOneDetailTwoCycleList[key].findIndex((item) => item.id === id);
				if (index > -1) {
					this.maintenanceLevelOneDetailTwoCycleList[key][index].status = status;
					//选择任意一个就认为是润滑了
					this.maintenanceLevelOneDetailTwoCycleList[key][index].whethermaintained = '1';
				}
			},
			showPic(filePath) {
				if (this.$commonUnits.isBankStr(filePath))
					return
				if (filePath.indexOf('/tmp/') !== -1 || filePath.indexOf('wxfile://tmp_') !== -1)
					return filePath;
				else
					//不是临时照片，需要拼上baseurl
					return this.baseUrl + filePath.replace(/\\/g, '/');
			},

			// 选择图片
			chooseImage(key, id) {
				if (this.isDisabled)
					return
				const item = this.maintenanceLevelOneDetailTwoCycleList[key].find(item => item.id === id);
				if (!item) return;

				const maxCount = 3 - (item.fileList?.length || 0);
				uni.chooseImage({
					count: maxCount,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						item.fileList = item.fileList === undefined ? [] : item.fileList;
						for (let tempFilePath in res.tempFilePaths) {
							item.fileList.push({
								filePath: res.tempFilePaths[tempFilePath]
							});
						}
					}
				});
			},

			// 选择图片
			chooseByImage() {
				if (this.isDisabled)
					return
				const maxCount = 3 - (this.byjhFileList?.length || 0);
				uni.chooseImage({
					count: maxCount,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						this.byjhFileList = this.byjhFileList === undefined ? [] : this.byjhFileList;
						for (let tempFilePath in res.tempFilePaths) {
							this.byjhFileList.push({
								filePath: res.tempFilePaths[tempFilePath]
							});
						}
					}
				});
			},

			// 预览图片
			previewImage(urls, current) {
				let onlyUrls = '';
				// 服务器图片要拼上baseurl
				if (urls[0].filePath.indexOf('/tmp/') === -1 && urls[0].filePath.indexOf('wxfile://tmp_') === -1) {
					onlyUrls = urls.map(item => {
						return this.baseUrl + item.filePath.replace(/\\/g, '/');
					});
				} else {
					onlyUrls = urls.map(item => {
						return item.filePath.replace(/\\/g, '/');
					});
				}
				uni.previewImage({
					urls: onlyUrls,
					current: onlyUrls[current]
				});
			},

			// 删除图片
			deleteImage(fileList, imageIndex) {
				if (this.isDisabled)
					return
				fileList.splice(imageIndex, 1);
			},

			// 切换标记状态
			toggleMarkAll() {
				if (!this.isAllMarked) {
					this.markAllNormal();
				} else {
					this.unmarkAll();
				}
			},

			// 一键合格
			markAllNormal() {
				uni.showModal({
					title: '确认提示',
					content: '确定将所有检查项标记为正常吗？',
					success: (res) => {
						if (res.confirm) {
							for (const key in this.maintenanceLevelOneDetailTwoCycleList) {
								this.maintenanceLevelOneDetailTwoCycleList[key].forEach(item => {
									item.whethermaintained = '1';
									item.status = '1';
								})
							}
							uni.showToast({
								title: '全部标记为正常',
								icon: 'success'
							});
							this.isAllMarked = !this.isAllMarked;
						}
					}
				});
			},

			//图片转换成base64
			readFileAsBase64(filePath) {
				return new Promise((resolve, reject) => {
					const fs = uni.getFileSystemManager();
					fs.readFile({
						filePath,
						encoding: 'base64',
						success: res => resolve(res.data),
						fail: err => reject(err)
					});
				});
			},

			// 取消所有标记
			unmarkAll() {
				uni.showModal({
					title: '确认提示',
					content: '确定取消所有检查项的标记吗？',
					success: (res) => {
						if (res.confirm) {
							for (const key in this.maintenanceLevelOneDetailTwoCycleList) {
								this.maintenanceLevelOneDetailTwoCycleList[key].forEach(item => {
									item.whethermaintained = '';
									item.status = '';
								})
							}
							uni.showToast({
								title: '已取消所有标记',
								icon: 'success'
							});
							this.isAllMarked = !this.isAllMarked;
						}
					}
				});
			},

			// 滚动到指定位置
			scrollToItem(id) {
				this.navIndex = '';
				this.$nextTick(() => {
					this.navIndex = id;
				});
			},

			//班组反馈
			async submitBzzConfirm() {
				let result = 0;
				//提交前检查
				for (const key in this.maintenanceLevelOneDetailTwoCycleList) {
					for (const item of this.maintenanceLevelOneDetailTwoCycleList[key]) {
						//统计未反馈的润滑项目数量
						if (this.$commonUnits.stringIsBlank(item.whethermaintained)) {
							uni.showToast({
								title: '请填写所有润滑项结果',
								icon: 'none'
							});
							this.scrollToItem(item.id);
							result = 1;
							return 0;
						}
					}
					if (result === 1) {
						return 0;
					}
				}
				//防抖。重复提交
				this.isDoubleClickDisabled = true;
				//准备反馈表数据
				this.submitData = [];
				for (const key in this.maintenanceLevelOneDetailTwoCycleList) {
					for (const item of this.maintenanceLevelOneDetailTwoCycleList[key]) {
						this.submitData.push(item);
						//处理每个润滑项目的附件
						if (item.fileList && item.fileList.length > 0) {
							item.fileList = await Promise.all(
								item.fileList.map(async (fileItem) => {
									const base64 = await this.readFileAsBase64(fileItem.filePath);
									return {
										...fileItem,
										base64,
									};
								})
							);
						}
					}
				}

				//处理润滑计划本身的附件
				if (this.byjhFileList && this.byjhFileList.length > 0) {
					this.byjhFileList = await Promise.all(
						this.byjhFileList.map(async (fileItem) => {
							const base64 = await this.readFileAsBase64(fileItem.filePath);
							return {
								...fileItem,
								base64,
							};
						})
					);
				}

				this.$commonUnits.postRequest("sbby.maintenancemobilebiz.submitMantenanceDetail.mobile", {
					userPic: this.userPic,
					equipmentId: this.equipmentId,
					userId: this.userId,
					planId: this.planId,
					remarks: this.byjhInfo.remarks,
					qualified: this.byjhInfo.qualified,
					details: this.submitData,
				}).then(item => {
					uni.hideLoading();
					if (item.res === 1) {
						uni.showToast({
							title: '提交成功',
							icon: 'success',
							duration: 2000,
							success: () => {
								this.$commonUnits.postRequest(
									"sbby.maintenancemobilebiz.savefile.mobile", {
										equipmentId: this.equipmentId,
										userId: this.userId,
										planId: this.planId,
										level: '1',
										detail: {
											fileList: this.byjhFileList
										},
									})

								setTimeout(() => {
									this.isDoubleClickDisabled = false;
									uni.navigateBack();
								}, 2000);
							}
						});
					} else {
						uni.showToast({
							title: '当前润滑计划已经存在记录，请勿重复提交。',
							icon: 'error',
							duration: 2000,
							success: () => {}
						});
					}
				})
			}
		}
	};
</script>

<style>
	.container {
		min-height: 100vh;
		background: #f5f7fa;
		padding-bottom: 120rpx;
	}

	.form-section {
		padding: 20rpx;
	}

	.form-group {
		background: #ffffff;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 20rpx;
	}

	.form-title {
		font-size: 28rpx;
		font-weight: 500;
		color: #333;
		margin-bottom: 20rpx;
		border-left: 4rpx solid #1890ff;
		padding-left: 12rpx;
	}

	.form-item {
		display: flex;
		align-items: center;
		padding: 16rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.form-item:last-child {
		border-bottom: none;
	}

	.label {
		min-width: 160rpx;
		color: #666;
		font-size: 26rpx;
	}

	.isQualified {
		flex: 1;
		display: flex;
		justify-content: space-between;
	}

	.value {
		flex: 1;
		color: #333;
		font-size: 26rpx;
	}

	/* 检查项目样式 */
	.check-list {
		margin-top: 10rpx;
	}

	.check-item {
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.check-item:last-child {
		border-bottom: none;
	}

	.check-header {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;
	}

	.check-name {
		font-size: 26rpx;
		color: #333;
	}

	.check-required {
		color: #ff4d4f;
		margin-left: 8rpx;
	}

	.check-options {
		display: flex;
		padding: 0 20rpx;
		gap: 20rpx;
	}

	.option {
		flex: 1;
		height: 64rpx;
		min-width: 160rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border: 1rpx solid #d9d9d9;
		border-radius: 6rpx;
		font-size: 26rpx;
		color: #666;
		box-sizing: border-box;
		padding: 0 20rpx;
	}

	.option.active {
		background: #e6f7ff;
		border-color: #1890ff;
		color: #1890ff;
	}

	.abnormal-desc {
		margin-top: 16rpx;
		width: 100%;
		height: 120rpx;
		padding: 16rpx;
		box-sizing: border-box;
		border: 1rpx solid #d9d9d9;
		border-radius: 6rpx;
		font-size: 26rpx;
		color: #333;
	}

	/* 图片上传区域样式 */
	.image-list {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
	}

	.image-item {
		width: 160rpx;
		height: 160rpx;
		position: relative;
	}

	.image-item image {
		width: 100%;
		height: 100%;
		border-radius: 6rpx;
	}

	.delete-btn {
		position: absolute;
		right: -10rpx;
		top: -10rpx;
		width: 40rpx;
		height: 40rpx;
		background: rgba(0, 0, 0, 0.5);
		border-radius: 50%;
		color: #ffffff;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
	}

	.upload-btn {
		width: 160rpx;
		height: 160rpx;
		border: 1rpx dashed #d9d9d9;
		border-radius: 6rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #999;
	}

	.plus {
		font-size: 48rpx;
		margin-bottom: 8rpx;
	}

	.upload-text {
		font-size: 24rpx;
	}

	/* 在现有样式基础上添加 */
	.form-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.quick-action {
		display: flex;
		align-items: center;
		padding: 8rpx 16rpx;
		background: #f6ffed;
		border-radius: 4rpx;
		border: 1rpx solid #52c41a;
		cursor: pointer;
	}

	.quick-action.is-marked {
		background: #fff1f0;
		border-color: #ff4d4f;
	}

	.action-text {
		font-size: 24rpx;
		color: #52c41a;
	}

	.quick-action.is-marked .action-text {
		color: #ff4d4f;
	}


	.action-icon {
		width: 32rpx;
		height: 32rpx;
		margin-right: 8rpx;
	}

	/* 图片上传样式 */
	.upload-images {
		margin-top: 20rpx;
	}

	.upload-btn {
		width: 160rpx;
		height: 160rpx;
		background: #fafafa;
		border: 1rpx dashed #d9d9d9;
		border-radius: 8rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.upload-icon {
		font-size: 40rpx;
		color: #999;
		line-height: 1;
		margin-bottom: 4rpx;
	}

	.upload-text {
		font-size: 24rpx;
		color: #999;
	}

	.upload-desc {
		font-size: 20rpx;
		color: #999;
		margin-top: 4rpx;
	}

	.image-list {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
		margin-top: 16rpx;
	}

	.image-item {
		position: relative;
		width: 160rpx;
		height: 160rpx;
	}

	.image-item image {
		width: 100%;
		height: 100%;
		border-radius: 8rpx;
	}

	.delete-btn {
		position: absolute;
		top: -16rpx;
		right: -16rpx;
		width: 32rpx;
		height: 32rpx;
		line-height: 32rpx;
		text-align: center;
		background: rgba(0, 0, 0, 0.5);
		color: #fff;
		border-radius: 50%;
		font-size: 24rpx;
	}

	/* 异常内容区域样式 */
	.abnormal-content {
		margin-top: 16rpx;
	}

	.upload-images {
		margin-top: 16rpx;
	}

	.image-list {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
	}

	.image-item {
		position: relative;
		width: 160rpx;
		height: 160rpx;
	}

	.image-item image {
		width: 100%;
		height: 100%;
		border-radius: 8rpx;
	}

	.delete-btn {
		position: absolute;
		top: -16rpx;
		right: -16rpx;
		width: 32rpx;
		height: 32rpx;
		line-height: 32rpx;
		text-align: center;
		background: rgba(0, 0, 0, 0.5);
		color: #fff;
		border-radius: 50%;
		font-size: 24rpx;
	}

	.upload-btn {
		width: 160rpx;
		height: 160rpx;
		background: #fafafa;
		border: 1rpx dashed #d9d9d9;
		border-radius: 8rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.upload-icon {
		font-size: 40rpx;
		color: #999;
		line-height: 1;
		margin-bottom: 4rpx;
	}

	.upload-text {
		font-size: 24rpx;
		color: #999;
	}

	.upload-desc {
		font-size: 20rpx;
		color: #999;
		margin-top: 4rpx;
	}

	/* 备注信息样式 */
	.remarks {
		width: 100%;
		height: 160rpx;
		padding: 16rpx;
		box-sizing: border-box;
		border: 1rpx solid #d9d9d9;
		border-radius: 6rpx;
		font-size: 26rpx;
		color: #333;
	}

	/* 底部提交按钮固定定位 */
	.footer-submit {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(255, 255, 255, 0);
		padding: 20rpx 30rpx;
		z-index: 999;
		display: flex;
		gap: 5px;
	}

	/* 让页面内容不被底部按钮遮挡 */
	.container {
		padding-bottom: 160rpx;
		/* 根据按钮高度调整 */
	}

	/* 按钮样式调整 */
	.footer-submit button {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 32rpx;
		margin: 10rpx 0;
		background: #252b93;
		color: #fff;
		border-radius: 8rpx;
		flex: 1 1 auto;
	}

	.footer-submit button[disabled] {
		background: #ccc;
	}

	.footer-submit .revoke {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 32rpx;
		margin: 10rpx 0;
		background: #ff0000;
		color: #fff;
		border-radius: 8rpx;
	}

	.signaturePic {
		width: 100rpx;
		height: 32rpx;
	}
</style>